import re

from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
from django.utils.translation import ugettext, ugettext_lazy as _
from django.db.models import get_model
from django.db import models

import multiprofiles.utils as utils

UserClass = utils.get_user_class()


class SubclassingQuerySet(models.query.QuerySet):

    def __getitem__(self, k):
        result = super(SubclassingQuerySet, self).__getitem__(k)
        if isinstance(result, models.Model) :
            return result.as_leaf_class()
        else :
            return result

    def __iter__(self):
        for item in super(SubclassingQuerySet, self).__iter__():
            yield item.as_leaf_class()


class ProfileManager(models.Manager):
    def get_query_set(self):
        return SubclassingQuerySet(self.model)


class Profile(models.Model):

    class Meta:
        app_label = 'multiprofiles'
        abstract = True

    content_type = models.ForeignKey(ContentType, editable=False, null=True)
    user = models.ForeignKey(UserClass)
    objects = ProfileManager()

    def __unicode__(self):
        verbose_name = getattr(self._meta, 'verbose_name')
        verbose_name = re.sub(
            '(\w*)', 
            lambda x: x.group(0).capitalize(), 
            verbose_name
        )
        return ugettext(verbose_name)
    __str__ = __unicode__

    def __repr__(self):
        return '<%s>' % self.__class__.__name__

    def save(self):
        if(not self.content_type):
            self.content_type = ContentType.objects.get_for_model(self.__class__)
        self.save_base()

    def as_leaf_class(self):
        content_type = self.content_type
        model = content_type.model_class()
        if(model == Profile):
            return self
        return model.objects.get(id=self.id)